// https://threejs.org/examples/#webgl_loader_collada_skinning
import { 
  AmbientLight,
  AnimationAction,
  AnimationMixer,
  Clock,
  GridHelper,
  LoadingManager,
  Mesh,
  MeshNormalMaterial,
  MeshStandardMaterial,
  Object3D,
  PerspectiveCamera,
  PointLight,
  Scene, 
  SkeletonHelper, 
  TextureLoader, 
  WebGLRenderer
} from "three";
import stats from '../../utils/stats';
// 调用
import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls';
import { BVHLoader } from 'three/examples/jsm/loaders/BVHLoader';
import { GUI } from 'dat.gui';

let clock = new Clock();
let scene = new Scene();
let camera = new PerspectiveCamera(45, window.innerWidth/window.innerHeight, 0.1, 1000);
camera.position.set(0, 0, -300);

const renderer = new WebGLRenderer({ antialias: true });
renderer.setPixelRatio(window.devicePixelRatio);
renderer.setSize(window.innerWidth, window.innerHeight);

document.body.appendChild(renderer.domElement);

scene.add(new AmbientLight( 0xffffff, 0.2 ));
const lights = new PointLight(0xffffff, 0.8);
camera.add(lights);
scene.add( camera );
        
const trackballControls = new OrbitControls(camera, renderer.domElement);
// 调整场景位置
// trackballControls.target.set(0, 3, 0);

let mixer: AnimationMixer;

addLoader();

render();
function render() {
  stats.update();
  trackballControls.update();

  if (mixer) {
    mixer.update(clock.getDelta())
  }

  requestAnimationFrame(render);
  renderer.render(scene, camera);
}

function addLoader() {
  const loader = new BVHLoader();
  loader.load(
    '/models/amelia-dance/DanceNightClub7_t1.bvh',
    (result: any) => {
      console.log(result);
      // let mesh = result.models[0];
      let skletonHelper: any = new SkeletonHelper(result.skeleton.bones[0]);
      // 追加骨骼，用于动画
      skletonHelper.skeleton = result.skeleton;

      let boneContainer = new Object3D();
      // 动画居中显示
      boneContainer.translateX(-100);
      boneContainer.translateY(-70);
      boneContainer.add(result.skeleton.bones[0]);
      scene.add(skletonHelper);
      scene.add(boneContainer);

      // 设置动画
      mixer = new AnimationMixer(skletonHelper);
      mixer.clipAction(result.clip).setEffectiveWeight(1.0).play();

    }
  )
}

function addGUI(action: AnimationAction): void {
  const gui = new GUI();
  gui.add(action, 'enabled').name('启用动画').listen();
  gui.add(action, 'paused').name('暂停').listen();
  gui.add(action, 'stop').name('停止');
  gui.add(action, 'play').name('开始');
  gui.add(action, 'reset').name('重置');
}